package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/mysql"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookAddLogic {
	return &BookAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookAddLogic) BookAdd(in *bookrpc.BookAddRequest) (*bookrpc.BookAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("id = ?", in.UserId).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在")
	}

	var class mysql.Class
	mysql.DB.Debug().Where("name  = ?", in.ClassName).Find(&class)

	if class.ID == 0 {
		return nil, fmt.Errorf("您上传的分类名称不合规")
	}

	book := mysql.Book{
		UserId:  in.UserId,
		ClassId: int64(class.ID),
		Title:   in.Title,
		Image:   in.Image,
		Context: in.Context,
	}

	mysql.DB.Debug().Create(&book)

	return &bookrpc.BookAddResponse{
		BookId: int64(book.ID),
	}, nil
}
